<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import AvatarUpload from '@/components/AvatarUpload.vue'
import { getUserByIdUsingGet, updateUserInfoUsingPut } from '@/api/userController.ts'

interface Props {
  isOpen?: boolean
  closeModal?: () => void
  refreshData?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  isOpen: false,
  closeModal: () => {},
  refreshData: () => {},
})

const user = ref<API.UserVo>({})

const getUserInfo = async (id: number) => {
  if (!id) {
    return
  }
  const res = await getUserByIdUsingGet({ id })
  if (res.code === 200 && res.data) {
    user.value = res.data as API.User
  } else {
    message.error(res.message)
  }
}

// 提交
const doSubmit = async () => {
  if (!user.value.id) {
    return
  }
  const res = await updateUserInfoUsingPut({
    ...user.value,
  })
  if (res.code === 200 && res.data) {
    message.success('修改成功')
    props.closeModal?.()
    props.refreshData?.()
  } else {
    message.error(res.message)
  }
}

// 回调函数
const onSuccess = (newUserAvatar: string) => {
  user.value.userAvatar = newUserAvatar
}

defineExpose({
  getUserInfo,
})
</script>

<template>
  <div id="user-detail-view">
    <a-modal
      v-model:open="props.isOpen"
      title="编辑用户信息"
      ok-text="提交"
      cancel-text="取消"
      @cancel="props.closeModal()"
      @ok="doSubmit"
    >
      <a-form :model="user">
        <a-form-item label="头像">
          <avatar-upload :user="user" :on-success="onSuccess" />
        </a-form-item>
        <a-form-item label="账号">
          <a-input v-model:value="user.userAccount" />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input v-model:value="user.userName" />
        </a-form-item>
        <a-form-item label="性别">
          <a-radio-group v-model:value="user.gender">
            <a-radio :value="0">男</a-radio>
            <a-radio :value="1">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="年龄">
          <a-input-number style="width: 100%" v-model:value="user.age" :min="1" :max="100" />
        </a-form-item>
        <a-form-item
          label="手机号"
          prop="phone"
          :rules="[
            {
              required: true,
              message: '请输入手机号',
            },
            {
              pattern: /^(?:13[0-9]|14[5-9]|15[0-3,5-9]|17[0-3,6-9]|18[0-9]|19[0-3,5-9])\d{8}$/,
              message: '请输入正确的手机号',
            },
          ]"
        >
          <a-input v-model:value="user.phone" />
        </a-form-item>
        <a-form-item label="收货地址">
          <a-input v-model:value="user.address" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped></style>
